/**
 * @file 厂商单工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 */

var dependsList = [
    'index', 'layer', 'form', 'table', '$http',
    'laydate', 'util', 'zmn_validate', 'zmnUtils','select2',
    'validator', 'Vue', 'dayjs','upload','element'
];

layui.define(dependsList, function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var validate = layui.zmn_validate;
    var util = layui.util;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var Vue = layui.Vue;
    var dayjs = layui.dayjs;
    var table = layui.table;
    var upload = layui.upload;
    var element = layui.element;
    var select2;

    window.EventBus = new Vue();

    var objOfURL = {
        workDetail: '/work/detail.action',
        workModifyDetail: '/work/modify/detail.action'
    };

    var options = {
        saveURL: null,
        isNew: false,
        isMemberOrder: false,
        modifyDetail: false,
        success: () => {}
    };

    // 城市
    var cityData = {};

    var NORMAL_ORDER_ADD_URL = '/order/normal/add.action';

    // 获取省份、城市、区域
    var CITY_URL = '/area/city/list.action';
    var COUNTY_URL = '/area/list.action';
    var AREA_DETAIL_URL = '/area/detail/list.action';
    var FUZZY_CITY_URL = '/area/city/fuzzy/list.action';

    // 获取产品列表
    var PRODUCT_URL = '/serv/product/list.action';
    var FUZZY_PRODUCT_URL = '/serv/fuzzy/product/list.action';
    // 获取产品服务类型
    var PRODUCT_SERV_URL = '/serv/factory/product/servCateg/list.action';
    // 获取常见故障
    var PRODUCT_SUBSIDIARY_URL = '/serv/factory/product/subsidiary/list.action';
    // 订单产品转化
    var CONVERT_PRODUCT_URL = '/serv/factory/product/convertProduct.action';
    // 厂商渠道转化
    var CONVERT_CHANNEL_ID_URL = '/channel/getChannelIdByFactoryId.action';

    // 检查返修单源单号
    var CHECK_REWORD_ID_URL = '/order/check/rework.action';

    // 产品几个表页面地址
    var PRODUCT_PRICE_TABLE_URL = '/order/getProductPriceTable';

    // 文件上传
    var UPLOAD_URL = '/order/factory/upload?factoryId=' ;

    // 文件上传
    var UPLOAD_PROGRESS_URL = '/order/factory/upload/progress?batchId=' ;

    let areaSize = 'auto';

    // 上传批次ID
    let batchId;


    /**
     * 页面结构
     */
    let cols = [[
        {field:'name', title:'姓名', width: 200, templet: '#userName'}
        ,{field:'telephone', title:'用户电话', width: 200, templet: '#telephone'}
        ,{field:'telephone2', title:'用户电话2', width: 200, templet: '#telephone2'}
        ,{field:'bizType', title:'业务类型', width: 200, templet: '#bizType'}
        ,{field:'city', title:'城市', width: 200, templet: '#remoteSelectForCityTemplate'}
        ,{field:'county', title:'区', width: 200, templet: '#remoteSelectForCountyTemplate'}
        ,{field:'address', title:'地址', width: 200, templet: '#address'}
        ,{field:'product', title: '服务产品', width: 200, templet: '#remoteSelectForProductTemplate'}
        ,{field:'count', title:'数量', width: 100, templet: '#count'}
        ,{field:'dutyTime', title:'预约时间', align: 'center', width: 400, templet: '#dutyTime'}
        ,{field:'fault', title:'其他故障', width: 300, templet: '#fault'}
        ,{field:'remark', title:'下单备注', width: 300, templet: '#remark'}
    ]];

    let tableData = function () {
        let arr = [];
        for (let i = 0 ; i < 10; i++) {
            arr.push({});
        }
        return arr;
    }();

    let tips = function (ele, str, callback) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        $(ele).focus();
        $(ele).val('');
        if (typeof callback === 'function') {
            callback();
        }
        return false;
    };

    let productCache = {};

    let loadIndex ;

    let timer ;

    /**
     * 操作提示
     * @param data
     */
    function toast(data) {
        layer.msg(data.title,{
            area: areaSize,
            icon:data.icon,
            time:data.time || 1000
        },function () {
            if(data.icon == 1){
                opCommonUtils.goOperateHome();
            }
        })
    }

    let tipsSelect = function (ele, str, callback) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        $(ele).addClass('layui-form-danger');
        $(ele).val('');
        if (typeof callback === 'function') {
            callback();
        }
        return false;
    };

    /**
     * 页面功能
     */

    function getLayuiSelectValue (selector) {
        return $(selector + ' option:selected').val();
    }

    /**
     * 全局获取器
     * @type {{getCityId: (function(): jQuery)}}
     */
    var getters = {
        getInputValueById: function (id) {
            return $.trim($('#' + id).val());
        },
        getLocation: function () {
            return {
                lng: $('#longitude').val(),
                lat: $('#latitude').val()
            };
        },
        getPlat: function () {
            return $('#plat').val() || 2;
        },
        getChannelId: function () {
            return $('#channelId').val();
        },
        getCityId: function () {
            return getLayuiSelectValue('#cityId');
        },
        getTelephone: function () {
            return this.getInputValueById('telephone');
        },
        getCountyId: function () {
            return this.getInputValueById('countyId');
        },
        getCityName: function () {
            return $('#cityId option:selected').text();
        },
        getStreet: function () {
            return $('#customerAddress').val();
        },
        getServCategId: function () {
            return getLayuiSelectValue('#servCategoryId');
        },
        getFcProductId: function () {
            return getLayuiSelectValue('#fcProductId');
        },
        getProductId: function () {
            return $('#productId').val();
        },
        getProductShowType: function () {
            return 2;
        },
        getFactoryId: function () {
            return getLayuiSelectValue('#factoryId');
        },
        getBizType: function () {
            return $('#bizType').val();
        },
        getDutyTime: function () {
            return $('#duty-time-input').val();
        },
        getWorkId: function () {
            return $('#work-id').val();
        },
        getOrderId: function () {
            return $('#order-id').val();
        },
        getCount: function () {
            var count  = $('#count').val();
            return Number.parseInt(count) || 0;
        },
        checkServicePoint: function () {
            var checkServicePoint  = $('#checkServicePoint').val();
            return checkServicePoint === 'true';
        },
        getOrderType: function () {
            return $('input[name="type"]:checked').val() || 1;
        },
        getPlatWork: function () {
            return $('#platWork').val() || $('#plat').val() || 1;
        },
        getLongitude: function () {
            return $('#longitude').val();
        },
        getLatitude: function () {
            return $('#latitude').val();
        },
        getAddress: function () {
            return $('input[name="address"]').val();
        }
    };

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }
    function getSelectText(item, ele) {
        return $(item).find(ele).find('option:selected').val();
    }

    // select选择框工作流
    let addressNode = {
        name: 'address',
        child: undefined,
        next: undefined,
        type: 3,
        multi: true
    };
    let productNode = {
        name: 'product',
        child: undefined,
        next: undefined,
        type: 3,
        multi: true
    };
    let countyNode = {
        name: 'county',
        child: undefined,
        next: undefined,
        type: 4,
        multi: true
    };
    let cityNode = {
        name: 'city',
        child: undefined,
        next: [productNode, countyNode],
        type: 2,
        multi: true
    };
    let factoryNode = {
        name: 'factory',
        child: $('select[name="product"]'),
        next: cityNode,
        type: 1,
        multi: false
    };


    function enableSelect(currValue, currEle, currNode) {
        let action = !currValue;
        // 启用
        // 点击厂商
        if (currNode.type === 1) {
            $.each($('select[name="city"]'), function (index, item) {
                $(item).val('');
                $(item).prop('disabled', false);
            });
            // 清空并禁用下级元素
            if (!action) {
                $.each($('select[name="product"]'), function (index, item) {
                    $(item).val('');
                    $(item).prop("disabled", true);
                });
            }
            currNode = currNode.next;
        }

        // 多节点元素判断

        if (currNode.multi) {
            if (Array.isArray(currNode.next)) {
                $.each(currNode.next, function (index, node) {
                    $.each($(currEle).parents('tr').find('select[name='+ node.name +']'), function (index, item) {
                        $(item).prop("disabled", action);
                    });
                });

            } else {
                $.each($(currEle).parents('tr').find('select[name='+ currNode.next.name +']'), function (index, item) {
                    $(item).prop("disabled", action);
                });
            }

        }

        // 禁用
        form.render('select');
    }

    /**
     * 根据厂商ID获取渠道ID
     * @param {string | number} factoryId 厂商ID
     */
    function fetchChannelId (factoryId) {
        return $http.$get(CONVERT_CHANNEL_ID_URL, {factoryId: factoryId})
    }

    /**
     * 远程获取产品数据
     * @param factoryId 厂商 id
     * @param cb 回调函数
     */
    function fetchProductData(params, cb) {
        return $http.get(PRODUCT_URL, params);
    }

    /**
     * 获取上传进度
     * @param batchId 批次id
     * @param cb 回调函数
     */
    function fetchProgressData(batchId, cb, fcb) {
        $http.$ajax({
            url: UPLOAD_PROGRESS_URL + batchId,
            type: 'GET',
            async: false
        }).then(cb, fcb);
    }


    /**
     * 格式化城市列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepo (repo) {
        if (repo.loading) {
            return '查询中...'
        }

        var name = repo.text;
        var markup = '<div><div><i class="zmn-icon zmn-icon-user"></i><span>' + name + '</span></div></div>';

        return markup;
    }

    /**
     * 使用 Select2 城市
     */
    function initCitySelectBySelect2 () {

        $('.select-city-remote').each(function (index) {
            var $this = $(this);
            $this.attr('id', $this.attr('id') + '-' + index);

            select2.initRemote({
                el: this,
                url: FUZZY_CITY_URL,
                getParams: function (params) {
                    let level = 3;
                    let cityId;
                    if ($this.hasClass("county")) {
                        level = 4;
                        cityId = $(this).parents('tr').find('select[name="city"]').val();
                    }

                    return {
                        keyWord: params.term,
                        level: level,
                        parentId: cityId
                    };
                },
                processor: function (data) {
                    return data.map((item) => {
                        item.id = item.value;
                        return item;
                    });
                },
                formatRepo: formatRepo
            });
        });
    }

    /**
     * 使用 Select2 产品
     */
    function initProductSelectBySelect2 () {

        $('.select-product-remote').each(function (index) {
            var $this = $(this);
            $this.attr('id', $this.attr('id') + '-' + index);

            select2.initRemote({
                el: this,
                url: FUZZY_PRODUCT_URL,
                getParams: function (params) {
                    let channelId = getters.getChannelId();
                    let cityId = $(this).parents('tr').find('select[name="city"]').val();
                    let bizType = $(this).parents('tr').find('select[name="bizType"]').val();
                    return {
                        keyWord: params.term,
                        channelId: channelId,
                        cityId: cityId,
                        bizType: bizType,
                        showType: 1
                    };
                },
                processor: function (data) {
                    return data.map((item) => {
                        item.id = item.value;
                        return item;
                    });
                },
                formatRepo: formatRepo
            });
        });
    }


    /**
     * 获取厂商对应的渠道ID
     */
    function initChannelId() {
        fetchChannelId(getters.getFactoryId()).then(function (data) {
            $("#channelId").val(data);
        }, function (msg) {
            layer.msg('无法获取厂商对应的ID', {
                area: areaSize
            });
            $("#channelId").val('');
        })
    }

    /**
     * 渲染服务品类选择下拉框
     * @param data 下拉框数据
     */
    function renderProductSelect(data, elem, productId) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function (index, item) {
            var productName = item.text;
            htmlStr += '<option value="' + item.value + '" data-unit="' + (item.ext1 || '') + '" ';
            if (productId === item.value) {
                htmlStr += 'selected=true'
            }
            htmlStr += '>' + productName + '</option>';
        });
        $(elem).parents('tr').find('select[name="product"]').html(htmlStr);
        form.render('select');
    }

    /**
     *  初始化产品下拉框
     * @param {string} factoryId 厂商id
     */
    function initProductSelect (channelId, cityId, elem, productId) {
        let key = channelId + '-' + cityId;
        if (!productCache.key) {
            return fetchProductData({
                channelId: channelId,
                cityId: cityId,
                productShowType: 1,
                plat: 1
            }).then(function (data) {
                productCache.key = data;
                renderProductSelect(data, elem, productId);
            }, function (msg) {
                layer.msg('产品数据获取失败', {
                    area: areaSize
                });
                renderProductSelect([], elem);
            });
        } else {
            renderProductSelect(productCache.key, elem, productId);
        }
    }

    /**
     * 设置表单字段值
     * @param {object} values 表单值对象
     */
    function setFieldsValue (values) {
        layui.form.val('zmn-order-add-form', values);
    }

    /**
     * 验证页面数据
     */
    function verifyData() {
        let result = true;
        let $tr = $('.table-box').find('tr');
        $tr.each(function (i, item) {
            result = false;
            let userName = getText(item, 'input[name="userName"]');
            let telephone = getText(item, 'input[name="telephone"]');
            let telephone2 = getText(item, 'input[name="telephone2"]');
            let bizType = getSelectText(item, 'select[name="bizType"]');
            let productId = getSelectText(item, 'select[name="product"]');
            let count = getText(item, 'input[name="count"]');
            let cityId = getSelectText(item, 'select[name="city"]');
            let countyId = getSelectText(item, 'select[name="county"]');
            let address = getText(item, 'input[name="address"]');
            let remark = getText(item, 'textarea[name="remark"]');

            let date = getText(item, 'input[name="date"]');
            let hour = getSelectText(item, 'select[name="hour"]');
            let minute = getSelectText(item, 'select[name="minute"]');
            let dutyTime;
            if (date || hour || minute) {
                if (!date ) {
                    tips($(item).find('input[name="date"]'), '请选择预约时间');
                    return false;
                }
                if (!hour ) {
                    tipsSelect($(item).find('select[name="hour"]'), '请选择预约时间');
                    return false;
                }
                if (!minute ) {
                    tipsSelect($(item).find('select[name="minute"]'), '请选择预约时间');
                    return false;
                }
                dutyTime = date + ' ' + hour + ':' + minute + ':00';
            }

            // 判断本行中用户是否填写了数据
            if (!userName && !telephone && !productId && !count && !cityId && !countyId && !address && !dutyTime &&! remark) {
                result = true;
                return true;
            }

            // 校验
            if (!telephone) {
                tips($(item).find('input[name="telephone"]'), '请输入手机号');
                return false;
            }
            if (!cityId) {
                tipsSelect($(item).find('select[name="city"]'), '请选择城市');
                return false;
            }
            if (!countyId) {
                tipsSelect($(item).find('select[name="county"]'), '请选择区');
                return false;
            }
            if (!address) {
                tips($(item).find('input[name="address"]'), '请输入地址');
                return false;
            }
            if (!productId) {
                tipsSelect($(item).find('select[name="product"]'), '请选择服务产品');
                return false;
            }
            if (!count ) {
                tips($(item).find('input[name="count"]'), '请填写数量');
                return false;
            }
            result = true;
        });
        return result;
    }

    /**
     * 获取提交数据
     */
    function getNewOrderList () {

        let channelId = getters.getChannelId();
        let factoryId = getters.getFactoryId();

        let newOrderList = [];

        let $tr = $('.table-box').find('tr');
        $tr.each(function (i, item) {
            let temp = {};

            temp.channelId = channelId;
            temp.factoryId = factoryId;
            temp.userName = getText(item, 'input[name="userName"]');
            temp.telephone = getText(item, 'input[name="telephone"]');
            temp.telephone2 = getText(item, 'input[name="telephone2"]');
            temp.bizType = getSelectText(item, 'select[name="bizType"]');
            temp.productId = getSelectText(item, 'select[name="product"]');
            temp.count = getText(item, 'input[name="count"]');
            temp.cityId = getSelectText(item, 'select[name="city"]');
            temp.countyId = getSelectText(item, 'select[name="county"]');
            temp.address = getText(item, 'input[name="address"]');
            temp.fault = getText(item, 'textarea[name="fault"]');
            temp.remark = getText(item, 'textarea[name="remark"]');

            let date = getText(item, 'input[name="date"]');
            let hour = getSelectText(item, 'select[name="hour"]');
            let minute = getSelectText(item, 'select[name="minute"]');
            if (date && hour && minute) {
                let dutyTime = date + ' ' ;
                if (hour < 10) {
                    dutyTime += '0';
                }
                dutyTime += hour + ':' + minute + ':00';
                temp.dutyTime = dutyTime;
            }

            // 校验
            if (!temp.telephone || !temp.productId || !temp.count || !temp.cityId || !temp.countyId || !temp.address) {
                return true;
            }
            newOrderList.push(temp);

        });
        return newOrderList;

    }

    /**
     * 保存新订单
     * @param {object} params 订单信息
     * @param {function} cb 回调函数
     */
    function saveOrderInfo (params, btn) {
        // 移除禁用标示
        $('select,input').attr("disabled", false);

        return $http.lockSave(options.saveURL, params, btn);
    }

    /**
     * 初始化文件上传
     */
    function renderUploaderForWorkFile(factoryId) {
        let batchId = new Date().getTime() + Math.ceil(Math.random()*10);
        //选完文件后不自动上传
        upload.render({
            elem: '#chooseFile'
            , url: UPLOAD_URL + factoryId + '&batchId=' + batchId
            , auto: false
            , accept: 'file'
            , size: 4096
            , acceptMime: 'xls,xlsx'
            , exts: 'xls|xlsx'
            , bindAction: '#confirmUpload'
            , before: function () {
                $('#confirmUpload').addClass('layui-btn-disabled');
            }
            , done: function (res) {
                if (!res.statusBool) {
                    layer.close(loadIndex);
                    layer.msg(res.message, {
                        area: areaSize
                    });

                    return;
                } else {
                    layer.close(loadIndex);
                    $("#progressBar").removeClass("layui-hide");

                    //模拟loading
                    timer = setInterval(function(){
                        fetchProgressData(batchId, function (data) {
                            console.log(data);

                            if (data.exceptionFlag) {
                                clearInterval(timer);
                                shwoMessage(data.message, function () {
                                    layer.closeAll();
                                });
                                return;
                            }

                            element.progress('importProgressBar', data.progressRate);

                            if (data.endFlag) {
                                clearInterval(timer);
                                shwoMessage(data.message, function () {
                                    location.reload();
                                });
                            }
                        })
                    }, 1000);

                    return;
                }
            }
            , error: function (index, upload) {
                layer.close(loadIndex);
                return;
            }
        });
    }

    function shwoMessage(message, cb) {
        layer.open({
            type: 1,
            content: '<div class="content">' + message + '</div>',
            btn: ['我知道了'],
            btnAlign: 'c',
            area: '400px',
            yes: function () {
                cb();
            }
        });
    }

    /**
     * 弹出文件上传层
     */
    function openUploadBox() {
        layer.open({
            type: 1,
            title: '导入excel',
            area: ['600px', '230px'],
            offset: '220px',
            content: $('#batchUpload').html(),
        });
        // 页面元素生成后，绑定事件
        $("#chooseFile").on('click', function () {
            let factoryIdForUpload = $('#factoryIdForUpload').val();
            if (!factoryIdForUpload) {
                layer.msg("请先选择厂商", {
                    area: areaSize
                });
            }
        });

        form.render();
    }

    //补全0
    function completeDate(value) {
        return value < 10 ? "0" + value : value;
    }
        /**
     * 初始化时间select
     */
    function initDutytimeSelect(elem) {
        let hourHtml = '<option value="">时<option>';

        let selectDay = $(elem).val();

        let char = "-";
        let nowDate = new Date();
        let currHour = nowDate.getHours();
        let currDay = nowDate.getDate();
        let currMonth = nowDate.getMonth() + 1;
        let currYear = nowDate.getFullYear();
        let currDate = currYear + char + completeDate(currMonth) + char +completeDate(currDay);


        for (let i = 8 ; i <= 20 ; i++)
        {
            hourHtml += '<option value="'+ i +'" ';
            if (selectDay === currDate && currHour > i) {
                hourHtml += 'disabled'
            }
            hourHtml += '>'+ i +'</option>';
        }
        $(elem).parents('tr').find('select[name="hour"]').html(hourHtml);
        form.render('select');

    }
    function initMinuteSelect(selectedHour, currElem) {
        let minutesHtml = '<option value="">分<option>';

        let currHour = new Date().getHours();
        let currMinutes = new Date().getMinutes();

        // 00
        minutesHtml += '<option value="'+ '00' +'" ';
        if (currHour === selectedHour && currMinutes > 0) {
            minutesHtml += 'disabled'
        }
        minutesHtml += '>'+ '00' +'</option>';

        // 30
        minutesHtml += '<option value="'+ '30' +'" ';
        if (currHour === selectedHour && currMinutes > 30) {
            minutesHtml += 'disabled'
        }
        minutesHtml += '>'+ '30' +'</option>';

        $(currElem).parents('tr').find("select[name='minute']").html(minutesHtml);

        form.render('select');

    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('click', '.select2-container--disabled', function () {
            if ($(this).hasClass('select2-container--disabled')) {
                let disableLength = $(this).parents('tr').find('.select2-container--disabled').length;
                console.log(disableLength);
                if (!disableLength) {
                    return;
                } else if (disableLength === 3) {
                    layer.msg("请选择厂商");
                } else if (disableLength === 2) {
                    layer.msg("请选择城市");
                }
            }
        });

        // 厂商选择下拉框的点击事件处理器
        form.on('select(factory)', function (data) {
            var factoryId = data.value;

            // 初始化渠道信息
            initChannelId();

            // 启用服务产品select
            enableSelect(factoryId, data.elem, factoryNode);
        });
        // 服务类型选择下拉框的点击事件处理器
        $("select[name='city']").on('change', function () {
            let cityId = $(this).val();

            enableSelect(cityId, this, cityNode);
        });
        // 批量上传
        $("#uploadOrder").on("click",function (data) {
            openUploadBox();
        });
        // 批量上传
        form.on('select(factoryIdForUpload)', function (data) {
            let factoryId = data.value;
            // 初始化页面上传
            renderUploaderForWorkFile(factoryId);
        });

        // 保存确认按钮点击事件
        form.on('submit(confirmbtn)', function (data) {

            // 校验数据
            if( !verifyData() ) {
                return false;
            }
            // 保存
            var params = getNewOrderList();
            console.log(params);

            if (params.length <= 0 ) {
                layer.msg('请填写订单数据', {
                    area: areaSize
                });
                return false;
            }

            loadIndex = layer.open({type: 3});
            saveOrderInfo(params, data.elem).then(function (data) {
                layer.close(loadIndex);
                layer.msg('操作成功', {
                    icon: 1,
                    time: 1000,
                    area: areaSize
                }, function () {
                    location.reload();
                });
            }, function (msg) {
                layer.close(loadIndex);
                layer.msg(msg, {
                    area: areaSize
                });
            });
            return false;
        });

        // 小时选择后，处理分钟选择
        form.on('select(hour)', function (data) {
          initMinuteSelect(parseInt(data.value), data.elem);
        });

        // 小时选择后，处理分钟选择
        $('input').on('focus', function () {
            if ($(this).hasClass('danger')) {
                $(this).removeClass('danger');
            }
        });

        // 初始化页面所有的日期选择器
        layui.use('select2', function (select2Module) {
            select2 = select2Module;

            initCitySelectBySelect2();
            initProductSelectBySelect2();
        });
    }

    var verifyRules = {
        // 用户电话验证
        tel: function (value) {
            value = $.trim(value);

            if (value === '') {
                return;
            }
            if (validate.phone(value) || validate.tel(value)) {
               return;
            }

            return '不正确手机号';
        },
        // 产品数量
        count: function (value) {
            value = $.trim(value);
            if (value !== "") {
                if (!validate.isPosInt(value)) {
                    return '请正确填写产品数量';
                } else if (value > 10) {
                    return '产品数量的最大值为 10';
                } else {
                    return;
                }
            }
        },

        // 验证预约时间
        dutyTime: function (value) {
            if (!$("#duty-time-checkbox").is(':checked') && !value) {
				if(getters.getPlatWork()==platMark.YEYX || getters.getPlatWork()==platMark.YBWX) {
					return;// 言而有信，一步维修不需要预约时间校验
				}
                return '请选择预约时间!';
            }
            return;
        },

        // 验证长度
        maxLengthFactory: function (length) {
            return function (value) {
                if (value.length > length) {
                    return '输入字符超过最大长度，最大长度为：' + length;
                } else {
                    return;
                }
            };
        }
    };

    function initVerifyRules () {
        form.verify({
            tel: verifyRules.tel,
            count: verifyRules.count,
            dutyTime: verifyRules.dutyTime,
            maxLenTo500: verifyRules.maxLengthFactory(500),
            maxLenTo300: verifyRules.maxLengthFactory(300),
            maxLenTo50: verifyRules.maxLengthFactory(50),
            maxLenTo100: verifyRules.maxLengthFactory(1000),
        });
    }

    /**
     * 延迟加载
     * @param func 处理函数
     * @param timeout 延迟时间
     */
    function lazyLoad (func, timeout) {
        setTimeout(func, timeout || 0);
    }

    /**
     * 初始化页面
     */
    function initPage() {

        table.render({
            elem: "#formTable",
            cols: cols,
            data: tableData,
            limit: 10
        });
        //同时绑定多个
        lay('.date').each(function(){
            laydate.render({
                elem: this
                ,min: 0
                ,trigger: 'click'
                ,done: function(value, date, endDate){
                    console.log(this.elem);
                    console.log($(this.elem).val());

                    initDutytimeSelect(this.elem);
                }
            });
        });

        form.render();

        // 初始化页面事件
        initEvent();

        // 初始化表单验证规则
        initVerifyRules();

    }

    exports("oms_order_batchAdd_common_factory", {
        init: function (ops) {
            options = ops;
            // 初始化页面
            initPage();
        }
    });
});